﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;

namespace AutoParsers.WebsiteParsers
{
    class CarGeParser : IAutoParser
    {

        public ParsedCar ParseAuto(string url)
        {

            ParsedCar myCar = new ParsedCar();

            string autoGeCarId  = String.Empty;

             System.Diagnostics.Process.Start("explorer.exe", @"C:\" + autoGeCarId);


            try
            {
                autoGeCarId = url.Substring(url.IndexOf("id") + 2, url.IndexOf("/") - 1);

                using (WebClient client = new WebClient())
                {
                    client.Encoding = System.Text.Encoding.UTF8;
                    var doc = new HtmlAgilityPack.HtmlDocument();
                    doc.LoadHtml(client.DownloadString(url));

                    myCar.URL = url;

                    var price = doc.DocumentNode.SelectSingleNode("//div[@class='price2']").InnerText.Trim(); // "\r\n\t23000 USD\t\r\n\t"                
                    myCar.Price = price;   // ფასი

                    var ganb_temp = doc.DocumentNode.SelectSingleNode("//div[@class='customs_passed']");

                    string ganbajeba;
                    string ganbajebis_pasi = String.Empty;

                    if (ganb_temp.ChildNodes[0].NextSibling == null)
                    {
                        ganbajeba = ganb_temp.ChildNodes[0].InnerText;
                        
                        //  myCar.ganbajeba = true;  // განბაჟებული             
                    }
                    else
                    {
                        ganbajeba = ganb_temp.ChildNodes[0].InnerText; // "\r\n\tგანუბაჟებელი&nbsp;(განბაჟება"
                        //myCar.ganbajeba = false;  // განუბაჟებელი

                        ganbajebis_pasi = ganb_temp.ChildNodes[1].InnerText;  // "&nbsp;1732$"
                        ganbajebis_pasi = ganbajebis_pasi.Substring(ganbajebis_pasi.IndexOf(";") + 1);
                        // myCar.ganbajebis_pasi = ganbajebis_pasi;     // განბაჟების ფასი 1732$
                    }


                    var user1 = doc.DocumentNode.SelectNodes("//div[@class='users']");
                    string user = user1[0].InnerText.Trim();

                    var user1Phone = doc.DocumentNode.SelectNodes("//div[@class='user_phone']");
                    string userPhone = user1Phone[0].InnerText.Trim();

                    myCar.Owner.FullName = user;
                    myCar.Owner.Mobile = userPhone;
                    //Owner ow = new Owner() {
                    //    FullName = user,
                    //    Mobile = userPhone
                    //};
      
                    string condition = doc.DocumentNode.SelectSingleNode("//div[@class='ddes']").InnerText;
                    myCar.Condition = condition;

                    var car_properties = doc.DocumentNode.SelectNodes("//div[@class='elem']");

                    myCar.Manufacturer = car_properties[0].LastChild.InnerText; // მწარმოებელი:
                    myCar.Model = car_properties[1].LastChild.InnerText;
                    myCar.Location = car_properties[2].LastChild.InnerText;
                    myCar.Year = car_properties[3].LastChild.InnerText; // გამოშვების წელი   
                    myCar.Engine = car_properties[4].LastChild.InnerText;
                    myCar.Mileage = car_properties[5].LastChild.InnerText;
                    myCar.Doors = car_properties[6].LastChild.InnerText;
                    myCar.Airbags = int.Parse(car_properties[7].LastChild.InnerText);
                    myCar.Transmission = car_properties[8].LastChild.InnerText;
                    myCar.Cylinders = int.Parse(car_properties[9].LastChild.InnerText);
                    if(car_properties[10].LastChild.InnerText.Equals("მარცხენა")) myCar.SteeringWheelAdjust = true;  // საჭე მარცხენა/მარჯვენა
                        myCar.SteeringWheelAdjust = false;
                   
                    myCar.WheelType = car_properties[11].LastChild.InnerText;
                    myCar.FuelType = car_properties[12].LastChild.InnerText;
                    myCar.Color = car_properties[13].LastChild.InnerText;
                    //myCar.mdgomareoba = car_properties[14].LastChild.InnerText; // am vels ar viReb


                    // myCar. = isOrNotIs(car_properties[15].InnerHtml);      // SesaZlebelia gacvla eseTi velia

                    myCar.ABS = isOrNotIs(car_properties[16].InnerHtml);    
                    myCar.ElMirrors = isOrNotIs(car_properties[17].InnerHtml);
                    myCar.ClimateControl = isOrNotIs(car_properties[18].InnerHtml);
                    //myCar.alloywheels = isOrNotIs(car_properties[19].InnerHtml);
                    myCar.SealingWax = isOrNotIs(car_properties[20].InnerHtml);
                    myCar.BoardComputer = isOrNotIs(car_properties[21].InnerHtml);
                    myCar.Alarm = isOrNotIs(car_properties[22].InnerHtml);
                    myCar.Parking = isOrNotIs(car_properties[23].InnerHtml);
                    myCar.AirConditioning = isOrNotIs(car_properties[24].InnerHtml);
                    myCar.LeatherInterior = isOrNotIs(car_properties[25].InnerHtml);
                    myCar.GPSNavigation = isOrNotIs(car_properties[26].InnerHtml);
                    myCar.CentralLocking = isOrNotIs(car_properties[27].InnerHtml);
                    myCar.Heated = isOrNotIs(car_properties[28].InnerHtml); // savarZlebis gaTboba
                    myCar.Hydraulics = isOrNotIs(car_properties[29].InnerHtml);
                    myCar.Turbo = isOrNotIs(car_properties[30].InnerHtml);


                    System.IO.Directory.CreateDirectory(@"C:\" + autoGeCarId);  //directory for car

                    var imageDivs = doc.DocumentNode.SelectNodes("//div[@class='thumb_images']");


                    //downloading images

                    if (imageDivs != null)
                    {
                       
                        foreach (var item in imageDivs[0].ChildNodes)
                        {
                            string n = item.InnerHtml.Trim(); if (n.Trim().Equals("")) continue;
                            else
                            {
                                string imageUrl, jpg = "jpg", jpeg = "jpeg"; string localFilename;
                                int j = n.IndexOf("http"); int jp = n.IndexOf(jpg);
                                if (jp != -1)
                                {
                                    imageUrl = n.Substring(j, n.IndexOf(jpg) - j + 3);
                                    myCar.Images.Add(imageUrl);
                                    localFilename = @"c:\" + autoGeCarId + "\\" + imageUrl.Substring(imageUrl.IndexOf(jpg) - 7);
                                }
                                else
                                {
                                    imageUrl = n.Substring(j, n.IndexOf(jpeg) - j + 4);
                                    myCar.Images.Add(imageUrl);
                                    localFilename = @"c:\" + autoGeCarId + "\\" + imageUrl.Substring(imageUrl.IndexOf(jpeg) - 7);
                                }
                                DownloadRemoteImageFile(imageUrl, localFilename);
                            }
                        }
                    }

                    #region comment
                    //creating text document

                    //using (TextWriter textWriter = File.CreateText(@"C:\" + autoGeCarId + "\\" + autoGeCarId + ".txt"))
                    //{
                    //    textWriter.WriteLine("ფასი: " + price);
                    //    textWriter.WriteLine("განბაჟება: " + ganbajeba);
                    //    textWriter.WriteLine("განბაჟების ფასი: " + ganbajebis_pasi);
                    //    textWriter.WriteLine("საკონტაქტო პირი: " + user);
                    //    textWriter.WriteLine("ტელეფონი: " + userPhone);
                    //    textWriter.WriteLine("კომენტარი: " + condition);


                    //    textWriter.Write(textWriter.NewLine + "###  ძირითადი მახასიათებლები  ###" + textWriter.NewLine + textWriter.NewLine);

                    //    for (int i = 0; i < car_properties.Count; i++)
                    //    {
                    //        if (car_properties[i].FirstChild.InnerText == "მდგომარეობა:") continue;
                    //        textWriter.Write(car_properties[i].FirstChild.InnerText + " ");

                    //        string sk = car_properties[i].InnerHtml;

                    //        //<span>პარკინგკონტროლი:</span><img src="/images/n.gif">	
                    //        //<span>fhი:</span>AUDI	

                    //        int sd = sk.IndexOf("<img");

                    //        if (sd != -1)
                    //        {
                    //            char c = sk.ElementAt(sd + 18);
                    //            if (c == 'n')
                    //                textWriter.Write("-");
                    //            else if (c == 'y')
                    //                textWriter.Write("+");

                    //            textWriter.WriteLine();
                    //        }
                    //        else
                    //        {
                    //            textWriter.WriteLine(car_properties[i].LastChild.InnerText);
                    //        }

                    //    }

                    //}
                    #endregion
                }

            }
            catch (Exception ex)
            {
                ex.StackTrace.ToString();
            }
            return myCar; // return ParsedCar Object

        }
               
                private bool isOrNotIs(string el)
                {  
                        char c = el.ElementAt(el.IndexOf("<img") + 18);
                        if (c == 'n')
                            return false;
                        
                        else if (c == 'y')
                            return true;

                     return true; // es ar unda Sesruldes
                       
                }

                //download and saves image 
                private static void DownloadRemoteImageFile(string uri, string fileName)
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    if ((response.StatusCode == HttpStatusCode.OK ||
                        response.StatusCode == HttpStatusCode.Moved ||
                        response.StatusCode == HttpStatusCode.Redirect) &&
                        response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
                    {
                        using (Stream inputStream = response.GetResponseStream())
                        using (Stream outputStream = File.OpenWrite(fileName))
                        {
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            do
                            {
                                bytesRead = inputStream.Read(buffer, 0, buffer.Length);
                                outputStream.Write(buffer, 0, bytesRead);
                            } while (bytesRead != 0);
                        }
                    }
                }     
   } 
}


